package com.cloudream.glsimple;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * Created by Administrator on 2018/10/12 0012.
 */

public class TrueTriangle extends AppCompatActivity {


    GLSurfaceView glSurfaceView = null;


    public static final float triangleCoords[] = {
            0.5f,  0.5f, 0.0f, // top
            -0.5f, -0.5f, 0.0f, // bottom left
            0.5f, -0.5f, 0.0f  // bottom right
    };

    //public static final float color[] = { 1.0f, 0.0f, 1.0f, 1.0f }; //白色


    private float[] mProjectMatrix = new float[16];
    private float[] mViewMatrix = new float[16];
    private float[] mMVPMatrix = new float[16];


    //顶点颜色
    private static final float color[] = {
            0.0f,1.0f,0.0f,1.0f,
            1.0f,0.0f,0.0f,1.0f,
            0.0f,0.0f,1.0f,1.0f
    };

    private static final String vertexShaderCode =
            "attribute vec4 vPosition;" +
            "uniform  mat4 vMatrix;" +
            "varying vec4 vColor;" +
            "attribute vec4 aColor;" +
            "void main(){" +
            "   gl_Position = vMatrix * vPosition;" +
            "   vColor = aColor;" +
            "}";


    private static final String fragmentShaderCode =
            "precision mediump float;" +
            "varying vec4 vColor;" +
            "void main(){" +
            "   gl_FragColor = vColor;" +
            "}";


    private FloatBuffer vertexBuffer = null;

    private FloatBuffer colorBuffer = null;
    // gles program handle
    private int mProgram;

    private int mPositionHandle;

    private int mColorHandle;

    private int mMatrixHandle;

    static final int COORDS_PER_VERTEX = 3;

    //顶点个数
    private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        glSurfaceView = new GLSurfaceView(this);
        setContentView(glSurfaceView);


        glSurfaceView.setEGLContextClientVersion(2);
        glSurfaceView.setRenderer(new MyTrueTriangleRender());
        glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);

    }


    public int loadShader(int type, String shaderCode){
        //根据type创建顶点着色器或者片元着色器
        int shader = GLES20.glCreateShader(type);
        //将资源加入到着色器中，并编译
        GLES20.glShaderSource(shader, shaderCode);
        GLES20.glCompileShader(shader);
        return shader;
    }


    private class MyTrueTriangleRender implements GLSurfaceView.Renderer{

        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            GLES20.glClearColor(0.5f,0.5f,0.5f,1.0f);
            ByteBuffer bb = ByteBuffer.allocateDirect(triangleCoords.length * 4);
            bb.order(ByteOrder.nativeOrder());

            vertexBuffer = bb.asFloatBuffer();
            vertexBuffer.put(triangleCoords);
            vertexBuffer.position(0);

            ByteBuffer dd = ByteBuffer.allocateDirect(color.length * 4);
            dd.order(ByteOrder.nativeOrder());
            colorBuffer = dd.asFloatBuffer();
            colorBuffer.put(color);
            colorBuffer.position(0);


            int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER,vertexShaderCode);
            int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER,
                    fragmentShaderCode);

            //create a opengles program
            mProgram = GLES20.glCreateProgram();
            // attach vertex shader to program
            GLES20.glAttachShader(mProgram,vertexShader);
            // attach fragment shader program
            GLES20.glAttachShader(mProgram,fragmentShader);
            // gles link program
            GLES20.glLinkProgram(mProgram);

        }

        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {
            // 设置视角
            GLES20.glViewport(0,0,width,height);

            float ratio = width*1.0f/height;
//            Matrix.frustumM (float[] m,         //接收透视投影的变换矩阵
//            int mOffset,        //变换矩阵的起始位置（偏移量）
//            float left,         //相对观察点近面的左边距
//            float right,        //相对观察点近面的右边距
//            float bottom,       //相对观察点近面的下边距
//            float top,          //相对观察点近面的上边距
//            float near,         //相对观察点近面距离
//            float far)          //相对观察点远面距离

            //设置 透视投影
            Matrix.frustumM(mProjectMatrix,0,-ratio,ratio,-1,1,6,7);

            //设置相机位置
            Matrix.setLookAtM(mViewMatrix,0,0,0,7.0f,
                    0f,0f,0f,
                    0f,1.0f,0.0f);

            Matrix.multiplyMM(mMVPMatrix,0,mProjectMatrix,0,mViewMatrix,0);


        }

        @Override
        public void onDrawFrame(GL10 gl) {
            GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT|GLES20.GL_DEPTH_BUFFER_BIT);

            GLES20.glUseProgram(mProgram);
            // get vMatrix handle
            mMatrixHandle = GLES20.glGetUniformLocation(mProgram, "vMatrix");
            // set vMatrix value
            GLES20.glUniformMatrix4fv(mMatrixHandle,1,false,mMVPMatrix,0);


            mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
            GLES20.glEnableVertexAttribArray(mPositionHandle);

            GLES20.glVertexAttribPointer(mPositionHandle,COORDS_PER_VERTEX,GLES20.GL_FLOAT,
                    false,
                    COORDS_PER_VERTEX* 4,//偏移量
                    vertexBuffer
            );



            mColorHandle = GLES20.glGetAttribLocation(mProgram, "aColor");
            GLES20.glEnableVertexAttribArray(mColorHandle);
            GLES20.glVertexAttribPointer(mColorHandle,4,
                    GLES20.GL_FLOAT,false,
                    0,colorBuffer);



//            mColorHandle = GLES20.glGetUniformLocation(mProgram,"vColor");
            //GLES20.glUniform4fv(mColorHandle,1,color,0);



            GLES20.glDrawArrays(GLES20.GL_TRIANGLES,0,vertexCount);
            GLES20.glDisableVertexAttribArray(mPositionHandle);
            GLES20.glDisableVertexAttribArray(mColorHandle);
//            GLES20.glDisableVertexAttribArray(mColorHandle);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        glSurfaceView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        glSurfaceView.onPause();
    }
}
